<?php

namespace common\models;

use common\helpers\Helper;
use common\helpers\Image;
use common\Service\RedisService;
use Yii;
use common\models\Common;

/**
 * This is the model class for table "{{%portray}}".
 *
 * @property string $id
 * @property string $title
 * @property string $desc
 * @property string $images
 * @property integer $star_id
 * @property integer $create_time
 * @property integer $image_num
 * @property integer $status
 * @property string $tags
 * @property integer $view
 */
class Portray extends Common
{
    public static $fields = ['id','title','desc','images','star_id','create_time','image_num','status','tags','view','relation_star','x_img','y_img'];

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%portray}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['desc', 'images'], 'string'],
            [['star_id', 'create_time', 'image_num', 'status', 'view','id'], 'integer'],
            [['title'], 'string', 'max' => 150],
            [['tags'], 'string', 'max' => 100],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '标题',
            'desc' => '描述',
            'images' => '图片',
            'star_id' => '明星编号',
            'create_time' => '添加时间',
            'image_num' => '图片数量',
            'status' => '状态 1：显示 2：不显示',
            'tags' => '标签',
            'view' => '浏览量',
            'relation_star' => '相关明星'
        ];
    }

    public static function getPortrayByTags($tags = [],$currentPage = 1, $perPage = 10,$fields = []){
        $tagCount = count($tags);
        //没有查询条件 直接读取总的列表
        if($tagCount === 0) return static::getMaxViewPortray($currentPage,$perPage,$fields);

        $redisKey = '';
        //只有一个标签，直接读取该标签的数据即可
        if(count($tags) === 1){
            $redisKey = 'tagPortrayZset:'.trim($tags[0]['alias']);
        }else{ //这下面的代码基本执行不到 先留着后面可能需要
            $alias = array_column($tags,'alias');
            $alias = array_map(function($value){
                return 'tagPortrayZset:'.trim($value);
            },$alias);
            $redisKey = RedisService::zInterStore($alias);
        }

        $rs = RedisService::pageData($redisKey,$currentPage,$perPage,'zset');
        $rs['data'] = static::formatPortrays($rs['data'],$fields);
        return $rs;

    }

    public static function getMaxViewPortray($currentPage = 1, $perPage = 10,$fields = []){
        $rs = RedisService::pageData('portrayZset',$currentPage,$perPage,'zset');

        $rs['data'] = static::formatPortrays($rs['data'],$fields);

        return $rs;
    }

    public static function formatPortrays($portrayIds = [],$fields = []){
        $rs = [];

        if($portrayIds){
            empty($fields) && $fields = static::$fields;

            foreach ($portrayIds as $id){
                $portrayInfo = static::getPortrayById($id,$fields);
                $portrayInfo && $rs[] = $portrayInfo;
            }
        }

        return $rs;
    }

    public static function getPortrayById($portrayId = 0,$fields = []){
        $portrayInfo = [];
        $portrayId = intval($portrayId);
        if($portrayId == 0) return $portrayInfo;

        $fields = empty($fields) ? self::$fields : array_merge($fields,['x_img','y_img']);

        if(!in_array('star_id',$fields)) array_push($fields,'star_id');
//        if(!in_array('images',$fields)) array_push($fields,'images'); //TODO  优化

        $portrayInfo = RedisService::getHash("portray:".$portrayId,$fields);
        if(empty($portrayInfo)){
            $portrayInfo = Portray::find()
                ->where(['id' => $portrayId])
                ->select($fields)
                ->asArray()
                ->one();
        }
        if($portrayInfo){
            $portrayInfo = static::formatPortrayInfo($portrayInfo);
        }

        return $portrayInfo;
    }

    public static function formatPortrayInfo($portrayInfo = []){
        if(!empty($portrayInfo)){
            isset($portrayInfo['images']) && $portrayInfo['images'] = static::parseImages($portrayInfo['star_id'],$portrayInfo['images']);
            isset($portrayInfo['tags']) && $portrayInfo['tags'] = Tags::parseTagsByName($portrayInfo['tags']);
            $portrayInfo['x_img'] = Helper::parseImg('/start/'.$portrayInfo['x_img']);
            $portrayInfo['y_img'] = Helper::parseImg('/start/'.$portrayInfo['y_img']);
        }

        return $portrayInfo;
    }

    public static function getStarAllPortrays($starId = 0,$fields=[]){
        $starId = intval($starId);
        $portrayIds = Yii::$app->get('redis')->smembers('tagPortraySet:'.$starId);

        return static::formatPortrays($portrayIds,$fields);
    }

    /**
     * @desc 获取推荐的写真数据
     * @param int $limit
     * @param array $fields
     * @return array
     */
    public static function recommendPortrays($limit = 10,$fields = []){
        $redis = Yii::$app->get('redis');

        if((int)$redis->exists('recommendPortraySet') == 0){
            //推荐规则 取浏览量最高的500个或者流量最低的500个 作为抽取数据 把流量低的也推出来
            $rpsId = (int)$redis->get('rpsId');
            $portrayIds = [];
            if($rpsId % 3 == 0){
                $portrayIds = $redis->zrevrange('portrayZset',0,50);
            }else{
                $portrayIds = $redis->zrange('portrayZset',0,50);
            }

            $rpsId++;
            $rpsId > 100 && $rpsId = 0;
            $redis->set('rpsId',$rpsId);

            foreach ($portrayIds as $portrayId){
                $redis->sadd('recommendPortraySet',$portrayId);
            }
            $redis->expire('recommendPortraySet',2 * 60 * 60); //两个小时更新一次
        }

        $portrayIds = $redis->srandmember('recommendPortraySet',$limit);
        return static::formatPortrays($portrayIds,$fields);
    }

    /**
     * @desc 获取随机的写真数据
     * @param int $limit
     * @param array $fields
     * @param array
     * @return array
     */
    public static function randomPortrays($limit = 10, $fields = [],$outIds = []){
        $redis = Yii::$app->get('redis');

        $minId = 667;
        $maxId = (int)$redis->get('maxPortrayId');
        $maxId == 0 && $maxId = Portray::find()->max('id');

        $redis->set('maxPortrayId',$maxId);
        $redis->expire('maxPortrayId',12 * 60 * 60);

        $out = empty($outIds) ? false : true;

        $portrayIds = [];
        $i = 0;
        while ($i < $limit){
            if($out){
                $randomId = rand($minId,$maxId);
                if(!in_array($randomId,$outIds)){
                    $portrayIds[] = $randomId;
                    $i++;
                }
            }else{
                $portrayIds[] = rand($minId,$maxId);;
                $i++;
            }
        }

        return static::formatPortrays($portrayIds,$fields);
    }


    /**
     * @desc 根据图片数量 确定内容分页总页数
     * @param $imageNum
     * @return float|int
     */
    public static function portrayContentTotalPage($imageNum){
        $totalPage = 1;
        if($imageNum <= 7) { //小于7张图片直接一次性返回
            $totalPage = 1;
        }
        if($imageNum > 7){
            $totalPage = ceil($imageNum / 5); //每五张图片一页
        }
        return $totalPage;
    }

    /**
     * @desc 获取内容分页图片内容
     * @param int $starId
     * @param $images
     * @param int $totalPage
     * @param int $currentPage
     * @param int $pageSize
     * @return array|mixed
     */
    public static function parseImages($starId,$images,$totalPage = 1,$currentPage = 1,$pageSize = 5){
        is_string($images) && $images = json_decode($images,true);
        if(empty($images)) return [];

        if($totalPage > 1){
            $images = array_slice($images,($currentPage - 1) * 5,$pageSize);
        }

        $rs = [];
        foreach ($images as $image){
            $rs[] = Helper::parseImg('/start/'.$image);
        }
        return $rs;

    }

    /*
     * 设置写真的封面图
     */
    public static function setXYImage($portrayId){
        ini_set("gd.jpeg_ignore_warning", 1);
        $portrayId = intval($portrayId);
        $portrayInfo = RedisService::getHash('portray:'.$portrayId,['star_id','images_info','images']);
        if(empty($portrayInfo)) return;
        //y_img:0.6911 x_img:1.4625
        if(isset($portrayInfo['images_info'])){
            $portrayInfo['images_info'] = json_decode($portrayInfo['images_info'],true);
            if(!empty($portrayInfo['images_info'])){
                $portrayInfo['images_info'] = array_map(function($value){
                    if(stripos($value['url'],'gtwImages') !== false){
                        $pathInfo = explode('/',$value['url']);
                        $value['url'] = $pathInfo[5].'/'.$pathInfo[6] . '/' . $pathInfo[7];
                    }
                    return $value;
                },$portrayInfo['images_info']);

                $xImg = $yImg = '';
                $xRatio = $yRatio = 0;
                foreach($portrayInfo['images_info']  as $i => $image){
                    if($i == 0){
                        $xRatio = abs($image['ratio'] - 1.4625);
                        $yRatio = abs($image['ratio'] - 0.6911);
                        $xImg = $yImg = $image['url'];
                    }

                    if(abs($image['ratio'] - 1.4625) < $xRatio){
                        $xRatio = abs($image['ratio'] - 1.4625);
                        $xImg = $image['url'];
                    }

                    if(abs($image['ratio'] - 0.6911) < $yRatio){
                        $yRatio = abs($image['ratio'] - 0.6911);
                        $yImg = $image['url'];
                    }
                }


                $newPortrayInfo = [];
                $newPortrayInfo['x_img'] = $xImg;
                $newPortrayInfo['y_img'] = $yImg;

                $portrayInfo['images'] = json_decode($portrayInfo['images'],true);
                foreach($portrayInfo['images'] as $key =>$image){
                    count(explode('/',$image)) == 2 && $newPortrayInfo['images'][$key] = $portrayInfo['star_id'].'/'.$image;
                }
                isset($newPortrayInfo['images']) && $newPortrayInfo['images'] = json_encode($newPortrayInfo['images']);

                $fileDirect = Yii::getAlias("@storage").'/start/';
                if(filesize($fileDirect.$xImg) > 150 * 1024){
                    $xImgInfo = explode('/',$xImg);
                    $xImgAddress = $fileDirect . $xImgInfo[0].'/'.$xImgInfo[1].'/'.'x_img.'.pathinfo($xImgInfo[2], PATHINFO_EXTENSION);
                    $rs = Image::mkThumbnail($fileDirect.$xImg,235 * 2,null,$xImgAddress);
                    $rs && $newPortrayInfo['x_img'] = str_replace($fileDirect,'',$xImgAddress);
                }

                if(filesize($fileDirect.$yImg) > 150 * 1024){
                    $yImgInfo = explode('/',$yImg);
                    $yImgAddress = $fileDirect . $yImgInfo[0].'/'.$yImgInfo[1].'/'.'y_img.'.pathinfo($yImgInfo[2], PATHINFO_EXTENSION);
                    $rs = Image::mkThumbnail($fileDirect . $yImg,235 * 2,null,$yImgAddress);
                    $rs && $newPortrayInfo['y_img'] = str_replace($fileDirect ,'',$yImgAddress);
                }
                RedisService::setHash('portray:'.$portrayId,$newPortrayInfo);
            }
        }

    }


}
